//
//  BasicWebViewController.m
//  CToolBox
//
//  Created by 张吉旭 on 17/3/15.
//  Copyright © 2017年 yj. All rights reserved.
//

#import "BasicWebViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>

@interface BasicWebViewController ()<UIWebViewDelegate>


@property (nonatomic,copy) NSString * webUrl;


@end

@implementation BasicWebViewController


- (id)initWithWebUrl:(NSString *)webUrl
{
    self = [super init];
    if (self) {
        
        _webUrl = webUrl;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self.view addSubview:self.webView];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_webUrl]]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    [_webView stopLoading];
    
}


-(UIWebView*)webView
{
    if (!_webView) {
        _webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
        _webView.backgroundColor = [UIColor whiteColor];
        _webView.delegate = self;
    }
    
    return _webView;
}



/**
 oc和js交互
 @param jsFunName 事件名称
 */
-(void)analysisJaveScrip:(NSString*)jsFunName
{
    JSContext *context = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    
    context[jsFunName] = ^() {
        NSArray *args = [JSContext currentArguments];
        
        NSMutableArray * jsArray = [NSMutableArray array];
        for (JSValue *jsVal in args) {
            [jsArray addObject:[jsVal toString]];
        }
    };

}


#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [AppDelegate showHUDWithView:self.view];
    });
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD hideHUDForView:[AppDelegate appDelegate].window animated:YES];
        
        [self analysisJaveScrip:@""];
    });
    
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD hideHUDForView:[AppDelegate appDelegate].window animated:YES];

    });
}

@end
